package org.example.thread4;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 线程池调用 - 给子线程命名
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2020/10/31 16:36
 */
public class MyThread2 extends Thread {
    private String threadName;

    public MyThread2(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public synchronized void run() {
        try {
            /**为当前线程设置名称*/
            Thread.currentThread().setName(threadName);
            System.out.println(new Date() + " 任务开始：" + Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(1 + new Random().nextInt(3));
            System.out.println(new Date() + " 任务结束：" + Thread.currentThread().getName());
            //...
            //Sat Oct 31 16:37:59 CST 2020 任务开始：崆峒七伤拳线程1
            //Sat Oct 31 16:38:00 CST 2020 任务结束：崆峒七伤拳线程1
            //Sat Oct 31 16:38:00 CST 2020 任务开始：崆峒七伤拳线程2
            //Sat Oct 31 16:38:00 CST 2020 任务结束：崆峒七伤拳线程0
            //...
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            MyThread2 myThread = new MyThread2("崆峒七伤拳线程" + i);
            /**线程池方式时,池中的线程是动态生成和管理的
             * 所以在这里做myThread.setName是没用的
             * 可以将名称传递过去，在run方法中进行设置
             * */
            executorService.execute(myThread);
            TimeUnit.SECONDS.sleep(1 + new Random().nextInt(1));
        }
    }
}
